package com.smedi.ismedi.web.starter.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.time.format.DateTimeFormatter;

/**
 * 定制 spring mvc 自带 Jackson 配制
 *
 * @author Zach
 * @date 11/14/20, 7:09 PM
 * @since 0.0.1
 */
@Configuration
@Slf4j
public class JacksonCustomize {

    @Value("${web-starter.date.date-format:yyyy-MM-dd}")
    private String dateFormat;

    @Value("${web-starter.date.date-time-format:yyyy-MM-dd['T'][' ']HH:mm[:ss]}")
    private String dateTimeFormat;

    @Value("${web-starter.date.date-time-format-serialize:yyyy-MM-dd[' ']HH:mm[:ss]}")
    private String dateTimeFormatSerialize;

    @Value("${web-starter.date.time-format:HH:mm[:ss]}")
    private String timeFormat;

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() {
        return jacksonObjectMapperBuilder -> {

            jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance);

            // 时间日期格式化
            jacksonObjectMapperBuilder.simpleDateFormat(dateFormat);

            // 序列化
            jacksonObjectMapperBuilder.serializers(new LocalTimeSerializer(DateTimeFormatter.ofPattern(timeFormat)));
            jacksonObjectMapperBuilder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
            jacksonObjectMapperBuilder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormatSerialize)));

            // 反序列化
            jacksonObjectMapperBuilder.deserializers(new LocalDateDeserializer(DateTimeFormatter.ofPattern(dateFormat)));
            jacksonObjectMapperBuilder.deserializers(new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(dateTimeFormat)));

        };
    }


}
